package cmd

import (
	"context"
	"time"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gcmd"
	"github.com/gogf/gf/v2/os/gsession"

	"myapp/internal/controller/access"
	"myapp/internal/controller/account"
	"myapp/internal/controller/member"
	"myapp/internal/controller/public"
	"myapp/internal/controller/role"

	"myapp/internal/service"
)

var (
	Main = gcmd.Command{
		Name:  "main",
		Usage: "main",
		Brief: "start http server",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			s := g.Server()

			// 使用redis作为session存储
			s.SetSessionMaxAge(time.Hour * 2)
			s.SetSessionStorage(gsession.NewStorageRedis(g.Redis()))

			setOpenAPIDoc(s)
			// s.SetSwaggerUITemplate(consts.MySwaggerUITemplate)

			routerRoot(s)

			s.Run()
			return nil
		},
	}
)

// 设置api接口
func setOpenAPIDoc(s *ghttp.Server) {
	openapi := s.GetOpenApi()
	openapi.Config.CommonResponse = ghttp.DefaultHandlerResponse{}
	openapi.Config.CommonResponseDataField = `Data`

	openapi.Info.Title = `goframe2`
	openapi.Info.Description = `基于 GoFrame2.8, VUE3, element-admin-plus的后台管理系统。  💖 `
}

func routerRoot(s *ghttp.Server) {
	mid := service.Middleware()
	s.Group("/v1",
		func(group *ghttp.RouterGroup) {
			group.Group("/public", func(group *ghttp.RouterGroup) {
				// 不需要登陆相关访问的接口: 登陆与注册等.
				group.Middleware(
					mid.CORS,
					mid.Ctx,
					ghttp.MiddlewareHandlerResponse,
				)
				group.Bind(
					//用户登陆
					member.NewV1(),
					public.NewV1(),
					// add more
				)
			})
			group.Group("/", func(group *ghttp.RouterGroup) {
				// 需要授权的
				group.Middleware(
					mid.CORS,
					mid.Ctx,
					mid.Auth,

					ghttp.MiddlewareHandlerResponse,
				)
				group.Bind(
					account.NewV1(),
					role.NewV1(),
					access.NewV1(),
				)
			})
			// session模式的登录验证
			group.Group("/session", func(group *ghttp.RouterGroup) {
				// 需要授权的
				group.Middleware(
					mid.CORS,
					mid.CtxWS,
					mid.Auth,
					ghttp.MiddlewareHandlerResponse,
				)
				group.Bind(
					account.NewV1(),
					// add more
				)
			})
		},
	)

}
